package com.yoomiito.app.ui.fragment

import android.Manifest
import android.content.Intent
import android.graphics.Color
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.provider.CalendarContract
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.BaseModel
import cn.droidlover.xdroidmvp.net.XApi
import com.gyf.barlibrary.ImmersionBar
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.yoomiito.app.ImmersionBarFragment
import com.yoomiito.app.MainActivity
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.base.WebViewActivity
import com.yoomiito.app.listener.OnViewClickListener
import com.yoomiito.app.model.LatLng
import com.yoomiito.app.model.bean.BannerAndIconInfo
import com.yoomiito.app.model.bean.UserInfo
import com.yoomiito.app.model.oil.OilBannerData
import com.yoomiito.app.model.oil.OilStationData
import com.yoomiito.app.model.oil.OilStationDetailData
import com.yoomiito.app.model.oilcard.OilCardData
import com.yoomiito.app.model.oilcard.OilCardInfo
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.showToast
import com.yoomiito.app.ui.anyview.gasstation.GasSortTabView
import com.yoomiito.app.ui.capture.CaptureActivity
import com.yoomiito.app.ui.yijiayou.*
import com.yoomiito.app.utils.*
import com.yoomiito.app.widget.SpacingDecoration
import com.yoomiito.app.widget.dialog.SelectMapDialog
import com.yoomiito.app.widget.dialog.SystemDialog
import com.yoomiito.app.widget.dialog.SystemTipDialog
import com.yoomiito.app.widget.dialog.TipDialog
import com.yoomiito.app.widget.state.ContentType
import com.yoomiito.app.widget.state.EmptyType_2
import com.yoomiito.app.widget.state.ErrorType
import com.yoomiito.app.widget.state.StatusManager
import kotlinx.android.synthetic.main.dialog_free_goods_coupon.view.*
import kotlinx.android.synthetic.main.fm_gas_station_list_2.*

class GasStationListFragment : ImmersionBarFragment<GasStationListPresenter_1>() {

    lateinit var frameLayout: FrameLayout
    lateinit var tabView: GasSortTabView
    lateinit var oilCardView: OilCardView
    private val mAdapter = GasStationListAdapter(null).also {
        it.setOnItemClickListener { adapter, view, position ->
            L.i("请求。。。。::: ${DebounceHelper.click(1)}")
//            DebounceHelper.click(1).compose(bindToLifecycle()).subscribe {_->
            L.i("开始请求。。。。")
            val data = it.data[position] as OilStationData
            if ("1" != UserInfoConfig.getUser().isOil) {
                showOilCardDialog()
                return@setOnItemClickListener
            }
            showLoading()
            YmApi.getYmService()
                    .oilCardInfo()
                    .compose(bindToLifecycle())
                    .compose(XApi.getApiTransformerData())
                    .compose(XApi.getScheduler())
                    .subscribe(object : ApiSubscriber<OilCardData>() {
                        override fun onSuccess(t: OilCardData?) {
                            dismissLoading()

                            if (t != null && !TextUtils.isEmpty(t.money) && t.money.toDouble() > 0) {
                                //调详情接口
                                if (data.type == 1) {
                                    val gps = GPSConverterUtils.gcj02_To_Bd09(latLng.lat, latLng.lng)
                                    oilDetail(data.gasId, latLng, LatLng(gps.lat, gps.lon), data.type)
                                } else {
                                    oilDetail(data.gasId, latLng, latLng, data.type)
                                }
                            } else {
                                "您的油米已不足，请充值后再次尝试".showToast()
                            }

                        }

                        override fun onFail(error: ApiException?) {
                            dismissLoading()
                            error?.msg?.showToast()
                        }

                    })
        }
//        }
        it.setOnItemChildClickListener { adapter, view, position ->
            val data = it.data[position] as OilStationData
            /*
            易加油 type=1 坐标为百度坐标
            团油 type=2 坐标为火星坐标系
            小桔 type=3 坐标为火星坐标系
             */
            if (data.type == 1) {
//                val converter = CoordinateConverter()
//                // CoordType.GPS 待转换坐标类型
//                converter.from(CoordinateConverter.CoordType.BAIDU)
//                // sourceLatLng待转换坐标点 LatLng类型
//                converter.coord(com.amap.api.maps2d.model.LatLng(data.lat.toDouble(), data.lng.toDouble()))
//                // 执行转换操作
//                val latlng: com.amap.api.maps2d.model.LatLng = converter.convert()
//                showSelectMap(latlng.latitude, latlng.longitude)
            } else {
                showSelectMap(data.lat.toDouble(), data.lng.toDouble())
            }

        }
    }
    var oilCardDialog: SystemDialog? = null
    private val mFreeBuyUrl = "https://mimitao-cdn.aijiamai.com/static/30@3x.png?"
    private fun showOilCardDialog() {
        val versionName = AllUtils.getVersionInfo().versionName
        val bannerAndIconInfo = BannerAndIconInfo()
        bannerAndIconInfo.bg_image_url = "https://mimitao-cdn.aijiamai.com/static/tc@3x.png?$versionName"
        bannerAndIconInfo.image_url = "https://mimitao-cdn.aijiamai.com/static/tc@3x.png?$versionName"
        if (oilCardDialog == null) {
            oilCardDialog = SystemDialog(context)
            oilCardDialog?.setBtnGoResId(R.drawable.icon_free_oil_card)
            oilCardDialog?.setmGoClickListener(OnViewClickListener { view: View? ->
                oilCardDialog?.dismiss()
                //获取加油卡
//                if (App.mAppConfig.isLogin) {
//                    oilCardDialog.dismiss()
//                    if ("1" == UserInfoConfig.getUser().isOil) {
//                        start(context, "")
//                    } else {
//                        showLoading()
//
//                    }
                showLoading()
                YmApi.getYmService()
                        .oilCard
                        .compose(bindToLifecycle())
                        .compose(XApi.getApiTransformerNoData<BaseModel<*>?>())
                        .compose(XApi.getScheduler())
                        .subscribe(object : ApiSubscriber<BaseModel<*>?>() {
                            override fun onSuccess(baseModel: BaseModel<*>?) {
                                YmApi.getYmService()
                                        .userInfo //
                                        .compose(bindToLifecycle())
                                        .compose(XApi.getApiTransformerData())
                                        .compose(XApi.getScheduler())
                                        .subscribe(object : ApiSubscriber<UserInfo?>() {
                                            override fun onSuccess(userInfo: UserInfo?) {
                                                setUserInfo(userInfo)
                                                dismissLoading()
                                            }

                                            override fun onFail(error: ApiException) {
                                                dismissLoading()
                                            }
                                        })
                                YmApi.getYmService()
                                        .oilCardInfo()
                                        .compose(bindToLifecycle())
                                        .compose(XApi.getApiTransformerData())
                                        .compose(XApi.getScheduler())
                                        .subscribe(object : ApiSubscriber<OilCardData>() {
                                            override fun onSuccess(t: OilCardData?) {
                                                dismissLoading()
                                                setInfo(t)
                                            }

                                            override fun onFail(error: ApiException?) {
                                                dismissLoading()
                                                error?.msg?.showToast()
                                            }

                                        })
                            }

                            override fun onFail(error: ApiException) {
                                dismissLoading()
                                error?.msg.showToast()
                            }
                        })

//                } else {
//                    //去登陆
//                    toOneKeyLogin((context as MainActivity))
//                }
            })
        }
        oilCardDialog?.setSystemDialogInfo(bannerAndIconInfo)
        oilCardDialog?.show()
    }

    private lateinit var mRefreshLayout: SmartRefreshLayout
    private lateinit var mRecyclerView: androidx.recyclerview.widget.RecyclerView
    private val mPaySuccessUrl = "https://mimitao-cdn.aijiamai.com/static/200@3x.png?"

    private var mCurrentPage = 1
    private lateinit var latLng: LatLng
    private var sortType = GasSortTabView.DistanceSort //默认距离优先
//    private var mLocationClient: AMapLocationClient? = null
    private val oilCardData = OilCardData()
//    private var option: AMapLocationClientOption? = null
//    private val mLocationListener = AMapLocationListener { p0 ->
//        L.i("定位结果错误信息：${p0?.errorCode}  ${p0?.errorInfo}")
//        L.i("定位结果：lat:${p0?.latitude} lng:${p0?.longitude} \n${p0?.address}")
//
//        dismissLoading()
//        when (p0?.errorCode) {
//            AMapLocation.LOCATION_SUCCESS -> { //
////                val gps1 = GPSConverterUtils.gcj_To_Gps84(p0?.latitude,p0?.longitude)
////                L.i("转换GPS： lat=${gps1.lat} lng=${gps1.lon}")
////                val gps2 = GPSConverterUtils.gcj02_To_Bd09(p0?.latitude,p0?.longitude)
////                L.i("转换BD： lat=${gps2.lat} lng=${gps2.lon}")
//                oilCardData.latitude = p0?.latitude //获取纬度信息
//                oilCardData.longitude = p0?.longitude//获取经度信息
////                oilCardData.longitude = 114.049881
////                oilCardData.latitude = 22.525394
//                latLng = LatLng(p0?.latitude, p0?.longitude)
//                requestList()
////                oilCardView.updateData(oilCardData)
//            }//定位成功
//            else -> "定位失败，请重试".showToast()
//        }
//    }

    override fun getLayoutId(): Int = R.layout.fm_gas_station_list_2

    override fun newP(): GasStationListPresenter_1 = GasStationListPresenter_1(App.mAppConfig)

    override fun initData(savedInstanceState: Bundle?) {
        view?.findViewById<LinearLayout>(R.id.back)?.visibility = View.INVISIBLE
        frameLayout = view?.findViewById(R.id.frameLayout)!!
        tabView = view?.findViewById(R.id.tabView)!!
//        oilCardView = view?.findViewById(R.id.oilCardView)!!
//        oilCardView.visibility = View.GONE
//        oilCardView.saoOnClickListener = {
//            if ("1" != UserInfoConfig.getUser().isOil) {
//                showOilCardDialog()
//            } else {
//                when (it) {
//                    OilCardView.SaoYiSao -> {
//                        AllUtils.requestPermission2(context as MainActivity, Manifest.permission.CAMERA).subscribe { per ->
//                            when {
//                                per.granted -> {
//                                    val intent = Intent(context, CaptureActivity::class.java)
//                                    startActivityForResult(intent, CaptureActivity.REQUESTCODE)
//                                }
//                                per.shouldShowRequestPermissionRationale -> {
//
//                                }
//                                else -> {
//                                    "请去设置中开启相机权限".showToast()
//                                }
//                            }
//                        }
//                    }
//                    OilCardView.BuyOilCard -> {
//                        oilCardView.buyOilCardReuest()
//                    }
//                }
//            }
//        }
        itemSearchDel.visibility = View.GONE
        itemSearch.background = ColorUtils.background(R.color.color_F4F4F4, 64f)
        itemSearchEt.let {
            it.hint = "搜索附近的油站"
//            it.isCursorVisible = false
            it.isFocusable = false
            it.isFocusableInTouchMode = false
        }
        itemSearchEt.setOnClickListener {
            if ("1" != UserInfoConfig.getUser().isOil) {
                showOilCardDialog()
            } else {
                if (this::latLng.isInitialized){
                    GasStationSearchActivity.start(context, latLng)
                }else{
                    "定位中".showToast()
                }
            }
        }
        search.setOnClickListener {
//            if ("1" != UserInfoConfig.getUser().isOil) {
//                showOilCardDialog()
//            } else {
//                OilCardDetailActivity.start(context)
//            }
            capture()
        }
        initAppbarLayout()
        initRcy()
        val shadeView = View(context)
        frameLayout.addView(shadeView, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        shadeView.setBackgroundResource(R.color.color_black_80)
        shadeView.visibility = View.GONE
        tabView.init(shadeView)
        tabView.onResultListener = {
            when (it) {
                -1 -> {//不处理
                }
                -2 -> {
                    sortType = GasSortTabView.DistanceSort
                    mAdapter.data.sortBy { sort -> sort.distance }
                    mAdapter.notifyDataSetChanged()

                }//距离优先
                -3 -> {
                    sortType = GasSortTabView.PriceSort
                    mAdapter.data.sortBy { sort -> sort.price }
                    mAdapter.notifyDataSetChanged()
                }//价格优先
                else -> {
                    oilNum = it
                    mCurrentPage = 1
                    showLoading()
                    requestList()
                }
            }
        }
        showLoading()
        banner()
        getOilCardInfo()
        initLocation()
        startLocation()
    }

    private fun capture(){
        AllUtils.requestPermission2(context as MainActivity, Manifest.permission.CAMERA).subscribe { per ->
            when {
                per.granted -> {
                    val intent = Intent(context, CaptureActivity::class.java)
                    startActivityForResult(intent, CaptureActivity.REQUESTCODE)
                }
                per.shouldShowRequestPermissionRationale -> {

                }
                else -> {
                    "请去设置中开启相机权限".showToast()
                }
            }
        }
    }

    private fun initLocation() {
//        mLocationClient = AMapLocationClient(context)
//        mLocationClient?.setLocationListener(mLocationListener)
//        mLocationClient?.setLocationOption(option())
    }

//    private fun option(): AMapLocationClientOption {
//        if (option == null) {
//            option = AMapLocationClientOption()
//            ////LocationMode.Hight_Accuracy：高精度；
//            ////LocationMode. Battery_Saving：低功耗；
//            ////LocationMode. Device_Sensors：仅使用设备；
//            option?.locationMode = AMapLocationClientOption.AMapLocationMode.Battery_Saving
//
//            option?.isOnceLocation = true //单次定位
//            //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。
//            //如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
//            option?.isOnceLocationLatest = true
//            option?.isNeedAddress = true //是否需要返回地址描述。
//            option?.httpTimeOut = 3000 //定位超时时间
//        }
//        return option!!
//    }

    private fun startLocation() {
        val lm = context.getSystemService(BaseActivity.LOCATION_SERVICE) as LocationManager
        val open = lm.isProviderEnabled(LocationManager.GPS_PROVIDER)//判断位置信息权限是否打开
        if (open) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                AllUtils.requestPermission3(context as MainActivity, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe { per ->
                            when {
                                per.granted -> {
                                    location()
                                }
                                per.shouldShowRequestPermissionRationale -> {

                                }
                                else -> {
                                    "请去设置中开启定位权限".showToast()
                                }
                            }
                        }
            } else {
                location()
            }
        } else {
            val dialog = TipDialog(context)
            dialog.setCancelText("取消")
            dialog.setSureText("去开启")
            dialog.setContent("请开启位置信息,以便寻找附近油站")
            dialog.setTitle("提示")
            dialog.setClickListener {
                dialog.dismiss()
                val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                context.startActivity(intent)
            }
            dialog.show()
        }
    }

    private fun location() {
        L.i("开始定位")
        showLoading()
//        mLocationClient?.startLocation()
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this)
                .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
                //                .navigationBarDarkIcon(true) //导航栏图标是深色，不写默认为亮色
                .fitsSystemWindows(true) //                .statusBarColor(R.color.colorPrimary)
                //                .statusBarDarkFont(true)
                //                .navigationBarColor(R.color.colorPrimary)
                .init()
    }

    private fun initAppbarLayout() {
        toolbarLl.setBackgroundResource(R.color.color_white)
//        appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, i ->
//            when {
//                i == 0 -> {//展开
//                    toolbarLl.setBackgroundResource(R.color.color_tran)
//                    titleTv.visibility = View.INVISIBLE
//                    val d = show_new.background as GradientDrawable
//                    d.setColor(ResUtil.getColor(R.color.color_FF035B))
//                }
//                abs(i) >= appBarLayout.totalScrollRange -> {//折叠
//                    toolbarLl.background = ColorUtils.gradient("#FFFF246C", "#FFFF035B")
//                    titleTv.visibility = View.VISIBLE
//                    val d = show_new.background as GradientDrawable
//                    d.setColor(ResUtil.getColor(R.color.color_tran))
//                }
//                else -> {//中间
//                    toolbarLl.setBackgroundResource(R.color.color_tran)
//                    titleTv.visibility = View.INVISIBLE
////                    if (abs(i)>=appBarLayout.totalScrollRange/2){
////                        appBarLayout.setExpanded(false,true)
////                    }else{
////                        appBarLayout.setExpanded(true,true)
////                    }
//                }
//            }
//        })
    }

    private fun initRcy() {
        mStatusManager = StatusManager.Builder(context)
                .addType(ContentType(R.layout.fm_rcy))
                .addType(EmptyType_2().setEmptyContent("未找到油站\n请更改筛选条件"))
                .addType(ErrorType().setMarginTop(98).setClickListener {
                    showLoading()
                    mCurrentPage = 1
                    requestList()
                })
                .build()
        mRefreshLayout = mStatusManager.view().findViewById(R.id.fm_refreshLayout)
        mRefreshLayout.setOnLoadMoreListener {
            mCurrentPage++
            requestList()
        }
        mRefreshLayout.setEnableRefresh(false)
        mRecyclerView = mStatusManager.view().findViewById(R.id.fm_rcy)
        frameLayout.addView(mStatusManager.view(), FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        mRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
        mRecyclerView.addItemDecoration(SpacingDecoration(0, DensityUtil.dp2px(5f), false))
        mRecyclerView.adapter = mAdapter
        showOrderTv.background = ColorUtils.gradientAndRadius("#80000000", "#80000000", 0f, 12f, 0f, 12f)
    }

//    private fun initBanner(bannerData: List<BannerAndIconInfo>) {
//        val data = mutableListOf<String>()
//        if (bannerData != null && bannerData.isNotEmpty()) {
//            bannerData.forEach {
//                data.add(it.image_url)
////                data.add("https://mimitao-cdn.aijiamai.com/FpBnbNVepoaMyfebOishmpXlomdB")
//            }
//        }
//        //设置banner样式
//        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
//        //设置图片加载器
//        banner.setImageLoader(BannerImageLoader())
//        //设置图片集合
//        banner.setImages(data)
//        //设置banner动画效果
//        banner.setBannerAnimation(Transformer.Default)
//        //设置标题集合（当banner样式有显示title时）
////        banner.setBannerTitles(titles);
//        //设置自动轮播，默认为true
//        banner.isAutoPlay(true)
//        //设置轮播时间
//        banner.setDelayTime(2500)
//        //设置指示器位置（当banner模式中有指示器时）
//        banner.setIndicatorGravity(BannerConfig.CENTER)
//        //banner设置方法全部调用完毕时最后调用
//        banner.setOnBannerListener {
//            ActTypeUtils.handleActFromType(context, bannerData[it])
//        }
//        banner.start()
//    }

//    private fun banner() {
//        p.banner()
//    }

    private fun requestList() {
        p.list(oilNum, latLng, mCurrentPage)
    }

    fun banner() {
        YmApi.getYmService()
                .oilBanner()
                .compose(bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<OilBannerData>() {
                    override fun onSuccess(t: OilBannerData?) {
                        dismissLoading()
                        t?.let {
                            showOrderTv.setData(it.discount)
                        }
                    }

                    override fun onFail(error: ApiException?) {
                        dismissLoading()
                    }

                })
    }

    fun setData(data: MutableList<OilStationData>?) {
        dismissLoading()
        if (data.isNullOrEmpty()) {
            if (mCurrentPage == 1) {
                mAdapter.setNewData(arrayListOf<OilStationData>())
                mStatusManager.showEmpty(EmptyType_2::class.java)
            } else {
                mRefreshLayout.finishLoadMoreWithNoMoreData()
            }
        } else {
            when (sortType) {
                GasSortTabView.DistanceSort -> {
                    data?.sortBy { sort -> sort.distance }
                }
                GasSortTabView.PriceSort -> {
                    data?.sortBy { sort -> sort.price }
                }
            }
            if (mCurrentPage == 1) {
                mAdapter.setNewData(data)
                mStatusManager.showContent()
                mRefreshLayout.setNoMoreData(false)
            } else {
                mAdapter.addData(data)
            }
            mRefreshLayout.finishLoadMore()
        }
    }

//    fun setBanner(data: OilBannerData?) {
//        data?.let {
//            initBanner(it.banner)
//            showOrderTv.setData(it.discount)
//        }
//    }

    fun showErrorView() {
        mRefreshLayout.finishLoadMore()
        if (mCurrentPage == 1) {
            mStatusManager.showError()
        } else {
            "数据请求超时，请稍后再试".showToast()
        }
    }

    override fun onStop() {
        super.onStop()
        dismissLoading()
    }

    var oilNum = GasSortTabView.DefaultOilNum

    fun oilDetail(id: String, transformLatLng: LatLng, originallatLng: LatLng, type: Int) {
        YmApi.getYmService()
                .stationDetail(id, transformLatLng.lng, transformLatLng.lat, originallatLng.lng, originallatLng.lat, type)
                .compose(bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<OilStationDetailData>() {
                    override fun onSuccess(t: OilStationDetailData?) {
                        if (t == null || (t.type == 2 && t.detail.isNullOrEmpty())) {//团油详情的油号可能为空
                            "油站数据有误，请稍后再试".showToast()
                        } else {
                            t?.let {
                                when (t.type) {
                                    2,4 -> {
                                        t.selectOilNum = oilNum
//                    t.selectOilNum = -40
                                        GasStationDetailActivity.start(context, t)
                                    }
                                    else -> {
                                        WebViewActivity.start(context, t.url)
                                    }
                                }
                            }
                        }
                    }

                    override fun onFail(error: ApiException?) {
                        dismissLoading()
                    }
                })
    }


    fun showSelectMap(lat: Double, lng: Double) {
        val dialog = SelectMapDialog(context, lat, lng)
        dialog.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == CaptureActivity.REQUESTCODE && data != null) {
            val result = data.getSerializableExtra(Const.Common.Data) as OilCardInfo
            showDialog(result)
        }
    }

    private fun showDialog(info: OilCardInfo) {
        val tipDialog = TipDialog(context)
        tipDialog.setCancelText("取消")
        tipDialog.setContent("是否确认充值至该账户？")
        tipDialog.setSureText("确定充值")
        tipDialog.setTitle("优米加油卡")
        tipDialog.setTitleVisible(true)
        tipDialog.setClickListener {
            tipDialog.dismiss()
            showLoading()
            actCode(info.code)
        }
        tipDialog.show()
    }

    private fun actCode(code: String) {
        YmApi.getYmService()
                .actOilCardCode(code)
                .compose(bindToLifecycle())
                .compose(XApi.getApiTransformerNoData<BaseModel<*>>())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<BaseModel<*>>() {
                    override fun onSuccess(t: BaseModel<*>?) {
                        getOilCardInfo()
                        showTipDialog(mPaySuccessUrl)
                    }

                    override fun onFail(error: ApiException?) {
                        dismissLoading()
                        error?.msg?.showToast()
                    }

                })
    }

    private fun showTipDialog(url: String) {
        val tipDialog = SystemTipDialog(context)
        tipDialog.setAdUrl(url)
        tipDialog.setIvWidthHeight(DensityUtil.dp2px(315f), DensityUtil.dp2px(182f))
        tipDialog.show()
    }

    fun getOilCardInfo() {
        YmApi.getYmService()
                .oilCardInfo()
                .compose(bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<OilCardData>() {
                    override fun onSuccess(t: OilCardData?) {
                        setInfo(t)
                    }

                    override fun onFail(error: ApiException?) {
                        setInfo(null)
                    }

                })
    }

    fun setInfo(t: OilCardData?) {
        dismissLoading()
        t?.let {
            oilCardData.money = it.money
            oilCardData.nums = it.nums
            oilCardData.totalDiscount = it.totalDiscount
            oilCardData.tips = it.tips
            oilCardData.address = it.address
//            if(this::oilCardView.isInitialized){
//                oilCardView.updateData(it)
//            }
//            tip.text = it.tips
//            if (!TextUtils.isEmpty(it.imgUrl))
//                ImageLoader.getInstance().into(this, it.imgUrl, explain3)
        }

    }

    override fun eventMessage(eventMessage: EventMessage?) {
        super.eventMessage(eventMessage)

        if (Type.EventMsgType.LoginSuccess == eventMessage?.eventType) {// || Type.EventMsgType.LoginOut==eventMessage?.eventType
//            showLoading()
            mCurrentPage == 1
            oilNum = GasSortTabView.DefaultOilNum
//                requestList()
            oilCardData.address = ""
            oilCardData.money = "0"
            oilCardData.nums = "0"
            oilCardData.totalDiscount = "0"
            oilCardData.tips = ""
            getOilCardInfo()
            startLocation()
        }
//        if (Type.EventMsgType.BuyComplete == eventMessage?.eventType && Type.EventMsgType.Success == eventMessage?.code) {
//            if (OilCardView.OilCardGoodsId==eventMessage?.goodsID){
//                getOilCardInfo()
//                showTipDialog(mPaySuccessUrl)
//            }
//        }
    }
}